package com.wbb.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wbb.mapper.TbBrandMapper;
import com.wbb.model.TbBrand;
import com.wbb.model.TbBrandExample;
import com.wbb.service.BrandService;
import com.wbb.util.queryParams;
import com.wbb.util.pageList;
import com.wbb.vo.BrandVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    private TbBrandMapper brandMapper;
    @Override
    public pageList<BrandVo> queryPage(queryParams<BrandVo> params) {
        Page<TbBrand> page = PageHelper.startPage(params.getPageNum(), params.getPageSize());
        TbBrandExample example = new TbBrandExample();
        if (params.getParams().getName() != null && !params.getParams().getName().isEmpty()){
            example.createCriteria().andNameLike("%"+params.getParams().getName()+"%");
        }
    // 根据条件查询所有数据
        List<TbBrand> tbBrands = brandMapper.selectByExample(example);
    // 获取pageInfo
        PageInfo<TbBrand> pageInfo = page.toPageInfo();

        List<TbBrand> list = pageInfo.getList();

        List<BrandVo> collect = list.stream().map(tb -> {
            BrandVo brandVo = new BrandVo();
            BeanUtils.copyProperties(tb, brandVo);
            return brandVo;
        }).collect(Collectors.toList());
        return new pageList<>(pageInfo.getTotal(),collect);
    }

    @Override
    public void deleteById(Long id) {
        brandMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void addBrand(BrandVo brandVo) {
        TbBrand tbBrand = new TbBrand();
        BeanUtils.copyProperties(brandVo,tbBrand);
        brandMapper.insertSelective(tbBrand);
    }

    @Override
    public void updateBrand(BrandVo brandVo) {
        TbBrand tbBrand = new TbBrand();
        BeanUtils.copyProperties(brandVo,tbBrand);
        brandMapper.updateByPrimaryKeySelective(tbBrand);
    }

    @Override
    public void patchDelete(List<Long> ids) {
        TbBrandExample example = new TbBrandExample();
        example.createCriteria().andIdIn(ids);
        brandMapper.deleteByExample(example);
    }

    @Override
    public List<BrandVo> getAll() {
        List<TbBrand> tbBrands = brandMapper.selectByExample(null);
        return tbBrands.stream().map(brand -> {
            BrandVo brandVo = new BrandVo();
            BeanUtils.copyProperties(brand, brandVo);
            return brandVo;
        }).collect(Collectors.toList());
    }
}